<?
class ccdsUserAdministration
	extends ccdsBackendPlugin
{
	public $name = "ccdsUserAdministration";

	private $objResponse = false;
	function __construct()
	{
		parent::__construct();

		$this->xajax = ccdsXajax::getInstance();

		$this->xajax->register( XAJAX_CCDS_FUNCTION, "UserAdministrationOpen", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "UserAdministrationUserDetailOpen", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "UserAdministrationUserDetail", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "UserAdministrationUserDetailSave", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "UserAdministrationUserFunctionsSave", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "UserAdministrationUserStructure", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "UserAdministrationUserStructureSave", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "UserAdministrationUserStructureListObjects", $this->name );



	}


	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function getAdminNavi($elements) {

		if (($_SESSION['CMS']['user_level'] >= 1000) OR ($_SESSION['CMS']['user_flags']['admin_user']))
		{
			$entry = array(
				'icon' => $this->config->get('LIBRARY_WEB').'famfamfam/icons/group.png',
				'onclick' => "xajax.request({ccdsfun:'UserAdministrationOpen',ccdsclass:'ccdsUserAdministration'},{parameters:[{}]});",
				'label' => $this->smarty->get_config_vars('AdminNaviPanel_user')
			);		
			$elements[0][] = $entry;
			return true;
		}
		return false;
	}


	function UserAdministrationOpen ( $aFormValues) 
	{

	  $objResponse = new ccdsResponse();
	
		$icon_src = $this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/page.png";
		$objResponse->loadcommands( $this->tools->addTabManager( 'topTab', "usergroups", "<img src=\"".$icon_src."\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">Users & Groups</span>" ) );
	
		$objResponse->clsTabManager->addPanel( "TabManagerContent_usergroups", array
		(
			"id" => "Coverview".$obj['obj_id'],
			"title" => "<img src=\"".$this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/application.png\" style=\"width:16px\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">Eigenschaften</span>",
			"content" => "<div id='ContentOverview_usergroups'></div>",
			"closeable" => false
		));
	  $user_chars = array();
	  $query = "SELECT DISTINCT(UPPER(SUBSTRING(user_name,1,1))) as zeichen FROM user WHERE user_del=0 order by zeichen";
	  $res = $this->ccdSQL->query($query);
	  while ($row = $this->ccdSQL->fetch_assoc($res)) {
	      $user_chars[] = $row['zeichen'];
	    }
	
	  $this->smarty->assign("user_chars",$user_chars);
	  $userlist = array();
	  $query ="SELECT * FROM user WHERE user_name LIKE '".addslashes($aFormValues['selected_char'])."%' AND user_del=0 ORDER BY user_name";
	  $res = $this->ccdSQL->query($query);
	  while ($row = $this->ccdSQL->fetch_assoc($res)) {
	      $userlist[] = $row;
	    }
	  $this->smarty->assign("selected_char",$aFormValues['selected_char']);
	  $this->smarty->assign("userlist",$userlist);
	  $sHtml = $this->smarty->fetch($this->tpl_dir."/user_list.tpl");
	  $objResponse->assign("ContentOverview_usergroups","innerHTML",$sHtml);
	  
	  return $objResponse;
	}

/* ---------------------------------------------------------------------------------------------------------------------------------- */




function UserAdministrationUserDetailOpen($aFormValues) {

  

  $objResponse = new ccdsResponse();

  $query ="SELECT * FROM user WHERE user_id='".addslashes($aFormValues['user_id'])."'";
  $res = $this->ccdSQL->query($query);
  $user= $this->ccdSQL->fetch_assoc($res);

  $this->smarty->assign("user",$user);
  
	$icon_src = $this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/page.png";
	$objResponse->loadcommands( $this->tools->addTabManager( 'topTab', "user_".$aFormValues['user_id'], "<img src=\"".$icon_src."\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">User: ".$user['user_name']."</span>" ) );

  $objResponse->loadcommands($this->UserAdministrationUserDetail($aFormValues));
  return $objResponse;

}

// ----------------------------------------------------------------------------------------------

function UserAdministrationUserDetail($aFormValues) {
  

  $objResponse = new ccdsResponse();

	$objResponse->clsTabManager->addPanel( "TabManagerContent_user_".$aFormValues['user_id'], array
	(
		"id" => "Coverview".$aFormValues['user_id'],
		"title" => "<img src=\"".$this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/application.png\" style=\"width:16px\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">&Uuml;bersicht</span>",
		"content" => "<div id='ContentOverview_user_".$aFormValues['user_id']."'></div>",
		"closeable" => false
	));


  $query ="SELECT * FROM user WHERE user_id='".addslashes($aFormValues['user_id'])."'";
  $res = $this->ccdSQL->query($query);
  $user= $this->ccdSQL->fetch_assoc($res);

  $this->smarty->assign("user",$user);

  $user_flags=array();
  $query = "SELECT * FROM user_flags WHERE user_flag_user_id='".addslashes($aFormValues['user_id'])."'";
  $res = $this->ccdSQL->query($query);
  while ($flag = $this->ccdSQL->fetch_assoc($res)) {
      $user_flags[$flag['user_flag_name']]=1;
    }
  $this->smarty->assign("user_flags",$user_flags);

  $languages = array();
  $query = "SELECT * FROM languages WHERE lang_active=1";
  $res = $this->ccdSQL->query($query);
  while ($row = $this->ccdSQL->fetch_assoc($res)) {
      $languages[] = $row;
    }
  $this->smarty->assign("languages",$languages);
  $sHtml .= $this->smarty->fetch($this->tpl_dir."/user_details.tpl");
  if ($aFormValues['user_id'] != "") {
    $objResponse->loadcommands($this->UserAdministrationUserFunctions($aFormValues));
    $objResponse->loadcommands($this->UserAdministrationUserStructure($aFormValues));
  }
  $objResponse->assign("ContentOverview_user_".$aFormValues['user_id'],"innerHTML",$sHtml);

  return $objResponse;

}
// ----------------------------------------------------------------------------------------------


function UserAdministrationUserFunctions($aFormValues) {
	
  $objResponse = new ccdsResponse();


  $query ="SELECT * FROM user WHERE user_id='".addslashes($aFormValues['user_id'])."'";
  $res = $this->ccdSQL->query($query);
  $user= $this->ccdSQL->fetch_assoc($res);


	$objResponse->clsTabManager->addPanel( "TabManagerContent_user_".$aFormValues['user_id'], array
	(
		"id" => "Cfunctions".$aFormValues['user_id'],
		"title" => "<img src=\"".$this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/application.png\" style=\"width:16px\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">Funktionen</span>",
		"content" => "<div id='ContentOverview_userFunctions_".$aFormValues['user_id']."'></div>",
		"closeable" => false
	));

  $this->smarty->assign("user",$user);

  $user_flags=array();
  $query = "SELECT * FROM user_flags WHERE user_flag_user_id='".addslashes($aFormValues['user_id'])."'";
  $res = $this->ccdSQL->query($query);
  while ($flag = $this->ccdSQL->fetch_assoc($res)) {
      $user_flags[$flag['user_flag_name']]=1;
    }
  $this->smarty->assign("user_flags",$user_flags);

  $languages = array();
  $query = "SELECT * FROM languages WHERE lang_active=1";
  $res = $this->ccdSQL->query($query);
  while ($row = $this->ccdSQL->fetch_assoc($res)) {
      $languages[] = $row;
    }
  $this->smarty->assign("languages",$languages);

  $sHtml = $this->smarty->fetch($this->tpl_dir."/user_rights.tpl");
  $objResponse->assign("ContentOverview_userFunctions_".$aFormValues['user_id'],"innerHTML",$sHtml);

  return $objResponse;	
	
}

// ----------------------------------------------------------------------------------------------

function UserAdministrationUserDetailSave($aFormValues) {
  

  $objResponse = new ccdsResponse();
  if ($aFormValues['user_id'] == "") {

      if ($aFormValues['user_login_pass'] != "") {

          if ($aFormValues['user_login_pass'] != $aFormValues['user_login_pass2']) {
	          $objResponse->script("$('<div/>').xWindow(
									'alert',	
									{
										title: 'Fehler: Passworteingabe',
										content: 'Die Passwörter stimmen nicht überein!'
									},function(){}
							);
							");
					}
          elseif ($aFormValues['user_name'] == "") {
	          $objResponse->script("$('<div/>').xWindow(
									'alert',	
									{
										title: 'Fehler: Benutzername',
										content: 'Bitte geben Sie einen Benutzernamen ein!'
									},function(){}
							);
							");
          }
          else {
              $query = "
                       INSERT INTO user
                       (
                       user_name,
                       user_email,
                       user_login_name,
                       user_login_pass,
                       user_interface_lang_id,
                       user_editor_lang_id,
                       user_level,
                       user_dir
                       
                       )
                       VALUES (
                       '".addslashes(trim($aFormValues['user_name']))."',
                       '".addslashes(trim($aFormValues['user_email']))."',
                       '".addslashes(trim($aFormValues['user_login_name']))."',
                       '".md5(trim($aFormValues['user_login_pass']))."',
                       '".addslashes(trim($aFormValues['user_interface_lang_id']))."',
                       '".addslashes(trim($aFormValues['user_editor_lang_id']))."',
                       '".addslashes(trim($aFormValues['user_level']))."',
                       '".addslashes(trim($aFormValues['user_dir']))."'
                       )
                       ";
              $this->ccdSQL->query($query);
              $user_id = $this->ccdSQL->insert_id();

              $objResponse->loadcommands($this->UserAdministrationUserDetailOpen(array("user_id"=>$user_id)));
            }
        } else {
          
          $objResponse->script("$('<div/>').xWindow(
								'alert',	
								{
									title: 'Fehler: Passworteingabe',
									content: 'Bitte geben Sie ein Passwort für den neuen Benutzer ein!'
								},function(){}
						);
						");
        }
    } else {
      if ($aFormValues['user_login_pass'] != "") {
          if ($aFormValues['user_login_pass'] != $aFormValues['user_login_pass2']) {

	          $objResponse->script("$('<div/>').xWindow(
									'alert',	
									{
										title: 'Fehler: Passworteingabe',
										content: 'Die Passwörter stimmen nicht überein!'
									},function(){}
							);
							");
              //AlertWindow($objResponse,"Fehler: Passworteingabe","Die Passwörter stimmen nicht überein!");
            } else {
              $query = "
                       UPDATE user SET
                       user_login_pass='".md5(trim($aFormValues['user_login_pass']))."'
                       WHERE user_id = '".$aFormValues['user_id']."'
                       ";
              $this->ccdSQL->query($query);

            }
        }

      $query = "
               UPDATE user SET
               user_name='".addslashes(trim($aFormValues['user_name']))."',
               user_login_name='".addslashes(trim($aFormValues['user_login_name']))."',
               user_email='".addslashes(trim($aFormValues['user_email']))."',
               user_editor_lang_id='".addslashes(trim($aFormValues['user_editor_lang_id']))."',
               user_interface_lang_id='".addslashes(trim($aFormValues['user_interface_lang_id']))."',
               user_level='".addslashes(trim($aFormValues['user_level']))."',
               user_del='".addslashes(trim($aFormValues['user_del']))."',
               user_dir='".addslashes(trim($aFormValues['user_dir']))."'

               WHERE user_id = '".$aFormValues['user_id']."'
               ";
      $this->ccdSQL->query($query);
    }

		$this->tools->notify($objResponse,"Der Benutzer wurde gespeichert!");

  return $objResponse;

}
// ----------------------------------------------------------------------------------------------

function UserAdministrationUserStructure($aFormValues) {

  

  $objResponse = new ccdsResponse();


  $query ="SELECT * FROM user WHERE user_id='".addslashes($aFormValues['user_id'])."'";
  $res = $this->ccdSQL->query($query);
  $user= $this->ccdSQL->fetch_assoc($res);


	$objResponse->clsTabManager->addPanel( "TabManagerContent_user_".$aFormValues['user_id'], array
	(
		"id" => "Cstructure".$aFormValues['user_id'],
		"title" => "<img src=\"".$this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/application.png\" style=\"width:16px\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">Struktur</span>",
		"content" => "<div id='ContentOverview_userStructure_".$aFormValues['user_id']."'></div>",
		"closeable" => false
	));

  $this->smarty->assign("user",$user);



  $projects = array();
  $query = "SELECT * FROM projects ORDER BY project_name";
  $res = $this->ccdSQL->query($query);
  while ($project = $this->ccdSQL->fetch_assoc($res)) {

      $query = "SELECT * FROM permissions_project_user WHERE project_user_key_project_id='".$project['project_id']."' AND project_user_key_user_id='".$aFormValues['user_id']."'";
      $p_res = $this->ccdSQL->query($query);
      if ($perm = $this->ccdSQL->fetch_assoc($p_res)) {
          $project['permissions'] = array(
                                      "read"=>$perm['project_user_read'],
                                      "modify"=>$perm['project_user_modify'],
                                      "new"=>$perm['project_user_new'],
                                      "delete"=>$perm['project_user_delete']
                                    );
        } else {
          $project['permissions'] = array(
                                      "read"=>0,
                                      "modify"=>0,
                                      "new"=>0,
                                      "delete"=>0
                                    );
        }

      $lang_id = $_SESSION['CMS']['user_lang_id'];
      $langs = array();
      $query = "SELECT * FROM mn_project_language WHERE project_language_key_project_id='".$project['project_id']."'";
      $res_lang = $this->ccdSQL->query($query);
      while ($lang = $this->ccdSQL->fetch_assoc($res_lang)) {
          $langs[] = $lang['project_language_key_language_id'];
        }
      if (!in_array($lang_id,$langs)) $lang_id = $langs[0];
      $pages = array();
      $query = "SELECT * FROM obj_index WHERE obj_parent_obj_id=0 AND obj_key_project_id='".$project['project_id']."'";
      $res2 = $this->ccdSQL->query($query);
      while($root = $this->ccdSQL->fetch_assoc($res2)) {
          $root = $this->tools->getObjectDetails($root['obj_id'],$lang_id);
          $root['permissions'] =$this->tools->PermissionsObj2UserGet($aFormValues['user_id'],$root['obj_id'],$user['user_level']);
          $root['count'] =($root['obj_id']);
          $pages[] = $root;
        }
      $project['subpages'] = $pages;
      $projects[]=$project;
    }
  $this->smarty->assign("projects",$projects);


  $sHtml = $this->smarty->fetch($this->tpl_dir."/user_structure.tpl");
  $objResponse->assign("ContentOverview_userStructure_".$aFormValues['user_id'],"innerHTML",$sHtml);

  return $objResponse;

}
// ----------------------------------------------------------------------------------------------


function UserAdministrationUserStructureListObjects($aFormValues) {

  

  $aFormValues['level'] += 18;

  $objResponse = new ccdsResponse();

  $query = "SELECT * FROM obj_index WHERE obj_id='".$aFormValues['obj_id']."'";
  $res = $this->ccdSQL->query($query);
  $obj = $this->ccdSQL->fetch_assoc($res);


  $query ="SELECT * FROM user WHERE user_id='".$aFormValues['user_id']."'";
  $res = $this->ccdSQL->query($query);
  $user= $this->ccdSQL->fetch_assoc($res);
  $this->smarty->assign("user",$user);

  $lang_id = $_SESSION['CMS']['user_lang_id'];
  $langs = array();
  $query = "SELECT * FROM mn_project_language WHERE project_language_key_project_id='".$obj['obj_key_project_id']."'";
  $res_lang = $this->ccdSQL->query($query);
  while ($lang = $this->ccdSQL->fetch_assoc($res_lang)) {
      $langs[] = $lang['project_language_key_language_id'];
    }
  if (!in_array($lang_id,$langs)) $lang_id = $langs[0];

  $pages = array();
  $query = "SELECT * FROM obj_index
           LEFT JOIN obj_names ON
           (obj_name_key_obj_id = obj_id AND obj_name_key_lang_id='".$lang_id."')
           LEFT JOIN
           classes ON
           (obj_key_class_id=class_id)
           LEFT JOIN templates ON
           (obj_key_tpl_id=tpl_id)



           WHERE obj_parent_obj_id='".$aFormValues['obj_id']."' AND (
           obj_deleted=0
           ) order by obj_position";
  $res = $this->ccdSQL->query($query);
  $pages = array();
  while ($row = $this->ccdSQL->fetch_assoc($res)) {
  		$names = $this->tools->getObjectName($row['obj_id'],$_SESSION['CMS']['user_lang_id']);
  		$row = array_merge($row,$names);
      $row['permissions'] =$this->tools->PermissionsObj2UserGet($aFormValues['user_id'],$row['obj_id'],$user['user_level']);
      $row['count'] = 1;//$this->tools->CountObjects($row['obj_id']);
      $pages[] = $row;
    }

  $this->smarty->assign("pages",$pages);
  $this->smarty->assign("level",$aFormValues['level']);
  $this->smarty->assign("prefix",$aFormValues['prefix']);
  $sHtml = $this->smarty->fetch($this->tpl_dir."/structure.tpl");

  $objResponse->contextAssign("target.innerHTML",$sHtml);

  return $objResponse;
}

// ----------------------------------------------------------------------------------------------

function UserAdministrationUserStructureSave($aFormValues) {
  
  $objResponse = new ccdsResponse();

  $regex = "/project_id_(\d*)_(.*?)$/";

  $obj_rights = array();
  $project_rights = array();
  foreach ($aFormValues as $key => $value) {
    if (preg_match_all($regex,$key,$res,PREG_SET_ORDER) > 0) {

        $project_id= $res[0][1];
        $action = $res[0][2];
        $project_rights[$project_id][$action]=1;
  	}
  }	

  $obj_regex = "/obj_(\d*)_(read|new|modify|delete)$/";
  foreach ($aFormValues as $key => $value) {
	  if (preg_match_all($obj_regex,$key,$res_objects,PREG_SET_ORDER) > 0) {
	      $obj_id=$res_objects[0][1];
	      $action=$res_objects[0][2];
	      $obj_rights[$obj_id][$action] = 1;
	    }
  }



	$query ="SELECT project_id FROM projects";
	$res = $this->ccdSQL->query($query);
	while ($row = $this->ccdSQL->fetch_assoc($res)) {
  	$project_id = $row['project_id'];

    if ($project_rights[$project_id]['read'] == "") $project_rights[$project_id]['read']=0;
    if ($project_rights[$project_id]['modify'] == "") $project_rights[$project_id]['modify']=0;
    if ($project_rights[$project_id]['delete'] == "") $project_rights[$project_id]['delete']=0;
    if ($project_rights[$project_id]['new'] == "") $project_rights[$project_id]['new']=0;


    $this->ccdSQL->query("DELETE FROM permissions_project_user WHERE 1
                AND project_user_key_user_id='".$aFormValues['user_id']."'
                AND project_user_key_project_id='".$project_id."'
                ");
    $this->ccdSQL->query("
                INSERT INTO permissions_project_user
                (
                project_user_key_project_id,
                project_user_key_user_id,
                project_user_read,
                project_user_modify,
                project_user_new,
                project_user_delete
                )
                VALUES (
                '".$project_id."',
                '".$aFormValues['user_id']."',
                '".$project_rights[$project_id]['read']."',
                '".$project_rights[$project_id]['modify']."',
                '".$project_rights[$project_id]['new']."',
                '".$project_rights[$project_id]['delete']."'

                );
                ");

  }



  foreach ($aFormValues['objects'] as $obj_id) {
    if ($obj_rights[$obj_id]['read'] == "") $obj_rights[$obj_id]['read']=0;
    if ($obj_rights[$obj_id]['modify'] == "") $obj_rights[$obj_id]['modify']=0;
    if ($obj_rights[$obj_id]['delete'] == "") $obj_rights[$obj_id]['delete']=0;
    if ($obj_rights[$obj_id]['new'] == "") $obj_rights[$obj_id]['new']=0;

    $result = $this->tools->PermissionsObj2UserSave($aFormValues['user_id'],$obj_id,$obj_rights[$obj_id]['read'],$obj_rights[$obj_id]['modify'],$obj_rights[$obj_id]['new'],$obj_rights[$obj_id]['delete']);
    if ($obj_rights[$obj_id]['subs']==1) {
        $this->tools->PermissionsObjSubs2UserSave($aFormValues['user_id'],$obj_id,$obj_rights[$obj_id]['read'],$obj_rights[$obj_id]['modify'],$obj_rights[$obj_id]['new'],$obj_rights[$obj_id]['delete']);
      }
  }

		$this->tools->notify($objResponse,"Die Einstellungen wurden gespeichert!");

  return $objResponse;
}

// ----------------------------------------------------------------------------------------------

function UserAdministrationUserFunctionsSave($aFormValues) {
  
  $objResponse = new ccdsResponse();
  $user_flags=array();
  $query = "DELETE FROM user_flags WHERE user_flag_user_id='".addslashes($aFormValues['user_id'])."'";
  $this->ccdSQL->query($query);

  if (is_array($aFormValues['user_flag'])) {
      foreach ($aFormValues['user_flag'] as $flag => $value) {
        $this->ccdSQL->query("INSERT INTO user_flags (user_flag_name,user_flag_user_id) VALUES('".$flag."','".addslashes($aFormValues['user_id'])."') ");
      }
    }
  return $objResponse;
}
// ----------------------------------------------------------------------------------------------


}


$ccdsModuleManager = ccdsModuleManager::getInstance();
$ccdsModuleManager->register('admin_navi','ccdsUserAdministration','getAdminNavi');